package com.lemon.stock.net

import com.lemon.stock.app.StockApplication
import com.lemon.stock.entity.Stock
import com.lemon.stock.util.sysStockMotion
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class SinaStock {

    companion object{
        fun send(liStock: List<String>, method: (s: String)-> Unit){
            var params = ""
            for (item in liStock) {
                params += "$item,"

            }
            if(params!=""){
                params = params.substring(0, params.length-1)
            }

            val repository = SinaRepositoryProvider.provideSearchRepository()
            repository.searchStock(params)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe({result->
                    print(result)
                    import(result)
                    method(result)
                },{
                        error-> error.printStackTrace()
                })
        }

        fun import(response: String){
            var arrRe = response.split("\n")
            val stockDao = StockApplication.getDataRoom().stockDao()
            //val siStock = stockDao.findById(id)
            for (item: String in arrRe) {
                val regex1 = Regex("\"(.+)\"")
                var result = regex1.find(item)?.value
                if(result!=null){
                    result = result.replace("\"", "")
                    val els = result.split(",")
                    //println(els[0])
                    val regex2 = Regex("([shz]+)([0-9]+)=")
                    var stocknum = regex2.find(item)?.value
                    //println()
                    val exchange = stocknum.toString().substring(0,2)
                    stocknum = stocknum.toString().substring(2,8)
                    var stock = stockDao.findById(stocknum)
                    if(stock==null){
                        stock = Stock(stockId=stocknum, stockName = els[0], stockExchange = exchange,
                            stockPrice = els[3].toFloat())
                        stockDao.insert(stock)
                    }else{
                        stock.stockPrice = els[3].toFloat()
                        sysStockMotion(stock)
                        stockDao.update(stock)
                    }
                }
            }
        }
    }











}